<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Date;
use Illuminate\Database\Eloquent\SoftDeletes;

class Content extends Model
{
    use HasFactory;

    const TYPE = [
        '工程' => 0,
        '求职' => 1,
        '招募合伙人' => 2,
        '租赁设备' => 3,
        '招聘' => 4,
    ];

    const IS_CHARGE = [
        1 => '付费',
        0 => '免费',
    ];

    const STATUS_DISABLEd = 0;
    const STATUS_ENABLED = 1;
    const STATUS_REJECTED = -1;

    const STATUS = [
        0 => '正常',
        1 => '正常',
        -1 => '已删除',
    ];

    protected $table = 'contents';
    protected $primaryKey = 'id';
    public $timestamps = true;
    protected $guarded = [];

    protected $casts = [
        'images' => 'array',
        'tags' => 'array',
        'data' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function position()
    {
        return $this->hasOne(Position::class, 'id', 'position_id');
    }

    public function scopeEnabled($query)
    {
        $query->where('status', '>=', 0);
    }

    public function userCollections()
    {
        return $this->hasMany(UserCollection::class, 'content_id', 'id');
    }

    public function userOrders()
    {
        return $this->hasMany(UserOrder::class, 'content_id', 'id');
    }

    public function getIsOwnerAttribute()
    {
        $userId = app('userId');
        if ($userId) {
            return $this->user_id == $userId;
        }
        return false;
    }

    public function getIsCollectedAttribute()
    {
        $userId = app('userId');
        if ($userId) {
            return $this->userCollections->pluck('user_id')->search($userId) !== false;
        }
        return false;
    }

    public function getIsBuyAttribute()
    {
        $userId = app('userId');
        if ($userId) {
            return $this->userOrders->pluck('user_id')->search($userId) !== false;
        }
        return false;
    }

    public function getTypeStrAttribute()
    {
        return array_search($this->type, self::TYPE);
    }

    public function getIsChargeStrStrAttribute()
    {
        return self::IS_CHARGE[$this->is_charge] ?? '未知';
    }

    public function getStatusStrAttribute()
    {
        return self::STATUS[$this->status] ?? '未知';
    }

    /**刷新内容 */
    public function refresh()
    {
        $now = Date::now();
        $this->refresh_at = $now;
        $refreshItem = new ContentRefresh([
            'content_id' => $this->id,
        ]);
        if ($refreshItem->save()) {
           return $this->save();
        }
        return false;
    }
}
